/*
 * @Author: wcx
 * @Email: 1055127249@qq.com
 * @Date: 2024-12-24 14:22:49
 * @LastEditors: wcx 1055127249@qq.com
 * @LastEditTime: 2025-01-21 15:25:45
 * @FilePath: \my-project\src\components\jsx\baseForm.js
 * @Description: 描述
 */
import { deepCopy } from '@/utils'
import elFormItems from '@/utils/formUtils'
export default {
  props: {
    fields: {
      type: Array,
      default: () => []
    },
    value: {
      type: Object,
      default: () => ({})
    },
    hideSubmit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {}
    }
  },
  mounted() {
    if (this.value) {
      this.form = deepCopy(this.value)
    }
  },
  watch: {
    form() {
      console.log(this.form)
      this.$emit('input', this.form)
    }
  },
  methods: {
    resetForm() {
      this.form = {}
    },
    getfield(field) {
      const { type, prop, props = {}, options = [] } = field
      const elItem = elFormItems.find(i => i.value === type)
      const childen = options.map(i => <el-option props={i}></el-option>)
      const domProps = {
        value: this.form[prop]
      }
      const on = {
        input: (value) => {
          console.log(value, this.form)
          this.form[prop] = value
          this.$emit('change', value, prop, this.form)
        }
      }
      return this.$createElement(elItem?.is || type, { props, on, domProps }, childen)
    },
    formItemsProps({ label, prop }) {
      return { label, prop }
    },
    createFields() {
      return this.fields.map(i => <el-form-item props={this.formItemsProps(i)}>{this.getfield(i)}</el-form-item>)
    },
    createButtons() {
      if (this.hideSubmit) return null
      return (
        <el-form-item>
          <el-button type="primary" onClick={() => this.$emit('onSubmit', this.form, this)}>提交</el-button>
          <el-button onClick={this.resetForm}>重置</el-button>
        </el-form-item>
      )
    },
  },
  render() {
    const onInput = (e) => { }
    return (
      <el-form ref="form">
        {this.createFields()}
        {this.createButtons()}
      </el-form>
    )
  }
}